const { spawn } = require("child_process")
const path = require('path')
const fs = require('fs')
const { nativeImage } = require('electron')
const fileUtil = require('../../../common/utils/fileUtil')
const uuidUtil = require('../../../common/utils/uuidUtil')
const { updatePluginFeatureByPluginModel } = require('../../../core/pluginSetupService/updatePluginFeature')

function getAppFromDarwin(resolve, reject) {
    let resultBuffer = new Buffer.from([]);

    const profileInstalledApps = spawn("/usr/sbin/system_profiler", [
        "-json",
        "-detailLevel",
        "mini",
        "SPApplicationsDataType"
    ]);

    profileInstalledApps.stdout.on("data", chunckBuffer => {
        resultBuffer = Buffer.concat([resultBuffer, chunckBuffer]);
    });
    profileInstalledApps.on("exit", exitCode => {
        if (exitCode !== 0) {
            reject([]);
            return;
        }
        try {
            let installedApps = JSON.parse(resultBuffer.toString()).SPApplicationsDataType.filter(app => {
                const appPath = app.path
                if (appPath.startsWith("/System/Applications") || appPath.startsWith("/Applications")) {
                    return true
                } else {
                    return false
                }
            })
            return resolve(installedApps)

        } catch (err) {
            console.info(err)
            reject(err);
        }
    });

    profileInstalledApps.on("error", err => {
        console.info(err)
        reject(err);
    });
}



function getIconByAppPath(appPath, pluginId) {
    const icondir = fileUtil.getPluginResoucePathByPluginId(pluginId)
    const name = uuidUtil.md5(appPath)
    const iconpath = path.join(icondir, `${name}.png`);
    const iconnone = path.join(icondir, `${name}.none`);
    const exists = fs.existsSync(iconpath);
    const existsnone = fs.existsSync(iconnone);
    if (exists) return `${name}.png`;
    if (existsnone) return null;


    const appName = appPath.split("/").pop() || "";
    const extname = path.extname(appName);
    const appSubStr = appName.split(extname)[0];
    const path1 = path.join(appPath, `/Contents/Resources/App.icns`);
    const path2 = path.join(appPath, `/Contents/Resources/AppIcon.icns`);
    const path3 = path.join(appPath, `/Contents/Resources/${appSubStr}.icns`);
    const path4 = path.join(appPath, `/Contents/Resources/${appSubStr.replace(' ', '')}.icns`);

    let iconPath = path1;
    if (fs.existsSync(path1)) {
        iconPath = path1;
    } else if (fs.existsSync(path2)) {
        iconPath = path2;
    } else if (fs.existsSync(path3)) {
        iconPath = path3;
    } else if (fs.existsSync(path4)) {
        iconPath = path4;
    } else {
        // 性能最低的方式
        const resourceList = fs.readdirSync(
            path.join(appPath, `/Contents/Resources`)
        );
        const iconName = resourceList.filter(
            (file) => path.extname(file) === ".icns"
        )[0];
        if (!iconName) {
            fs.writeFileSync(iconnone, "")
            return null;
        }
        iconPath = path.join(appPath, `/Contents/Resources/${iconName}`);
    }
    nativeImage.createThumbnailFromPath(iconPath, { width: 64, height: 64 }).then((img) => {
        const base64Data = img.toDataURL().replace(/^data:.+;base64,/, '"');
        const result = Buffer.from(base64Data, "base64");
        fs.writeFile(iconpath, result, "base64", () => {
            // todo
        });
    })

    return `${name}.png`
}


exports.updateDarwinApp = function (plugin) {
    if (plugin == null) { return }
    new Promise(getAppFromDarwin).then((apps) => {
        apps.map((item) => {
            item.icon = getIconByAppPath(item.path, plugin.pluginId)
        })

        updatePluginFeatureByPluginModel(compose(plugin, apps))
    })
}


function compose(plugin, apps) {
    const cmds = []
    apps.map((app) => cmds.push(composeFeature(app.icon, app._name, app.path)))
    plugin.pluginInfo.features = cmds
    return plugin
}




function composeFeature(iconPath, appName, appPath) {
    return {
        "code": "open",
        "name": appName,
        "desc": appPath,
        "icon": iconPath,
        "mode": "headless",
        "platform": [
            "darwin"
        ],
        "cmds": [
            {
                "decisionMethod": "initials",
                "decisionDataType": "keyword",
                "decisionDataSource": "search",
                "decisionData": appName
            }
        ]
    }
}